package com.sq.partner.manager.controller;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.common.exception.AppException;
import com.sq.partner.manager.mybatis.model.CoreDept;
import com.sq.partner.manager.mybatis.model.GatewayChannelInfo;
import com.sq.partner.manager.mybatis.model.GatewayCustomer;
import com.sq.partner.manager.mybatis.model.GatewayPolicy;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.NlifeCov;
import com.sq.partner.manager.mybatis.model.ScanCustomer;
import com.sq.partner.manager.mybatis.model.TradPlanBase;
import com.sq.partner.manager.mybatis.model.TreeDto;
import com.sq.partner.manager.service.IGatewayChannelInfoConfigService;
import com.sq.partner.manager.service.IGatewayCustomerService;
import com.sq.partner.manager.service.IGatewayProductService;
import com.sq.partner.manager.service.INlifeProdConfigService;
import com.sq.partner.manager.service.RuleConfigerService;
import com.sq.partner.manager.service.ScanPolicyListService;
import com.sq.partner.manager.util.DateUtil;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.SqlUtil;
import com.sq.partner.manager.util.StrUtil;

/**
 * 
 * @author Kang
 * 人险保单查询/lifePolicyList
 */
@Controller
@RequestMapping(value = "/scanPolicyList")
public class ScanPolicyListController {
	
	private static Logger logger = LogUtil.getLog(ScanPolicyListController.class);
	
	@Resource
	private ScanPolicyListService lifePolicyListService;
	
	@Resource
	private IGatewayChannelInfoConfigService channelInfoConfigService;
	
	@Resource
	private IGatewayProductService productService;
	
	@Resource
	private IGatewayCustomerService customerService;
	
	@Resource
	private RuleConfigerService ruleConfigerService;
	
	@Resource
	private INlifeProdConfigService nlifeProdConfigService;
	
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index(){
		return "transManager/ScanPolicyList";
	}
	

	/**
	 * 查询扫码相关合作伙伴
	 * @param fkAppid
	 * @return List<GatewayChannelInfo>
	 * @throws Exception 
	 */
	@RequestMapping(value = "/queryChannelInfoOfNLife",method = RequestMethod.POST)
	public @ResponseBody Page<GatewayChannelInfo> queryChannelInfoOfLife(Integer size,Integer pageIndex,
									String channelName,String channelCode) throws Exception{
		Page<GatewayChannelInfo> page = new Page<GatewayChannelInfo>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
		channelInfo.setChannelCode(channelCode);
		channelInfo.setChannelName(channelName);
		page.setType(channelInfo);
		return lifePolicyListService.queryChannelInfoPageOfFacadeNlife(page);
	}
	
	/**
	 * 人险保单查询和保单信息下载前进行验证
	 * @param session
	 * @param pageIndex
	 * @param policy
	 * @param privilegeBranch
	 * @param bbrName
	 * @param bbrCertiCode
	 * @param polSubDateBegin
	 * @param polSubDateEnd
	 * @param polBeginDateBegin
	 * @param polBeginDateEnd
	 * @return
	 * @throws Exception
	 */
	public Page beforeQueryLifePolicyPageByCriteria(HttpSession session, Integer pageIndex,GatewayPolicy policy,String userCode,
			String polSubDateBegin,String polSubDateEnd,String polBeginDateBegin,String polBeginDateEnd) throws Exception{
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		Page page = new Page();
		Map<String,Object> map = new HashMap<String, Object>();
		if(pageIndex != -1){
			page.setCurrent(pageIndex);
			map = SqlUtil.buildPageMap(page);
		}
		String privilegeBranch = "";
		if(user.getDepts()!=null){
			String[] split = user.getDepartmentStr().split(",");
			List<String> list = Arrays.asList(split);
			Collections.sort(list);
			privilegeBranch = list.get(0).substring(1, list.get(0).length()-1);
		}
		map.put("privilegeBranch",privilegeBranch);
		if(StrUtil.isNotEmpty(polSubDateBegin)){
			polSubDateBegin=polSubDateBegin+" 00:00:00";
		}
		if(StrUtil.isNotEmpty(polSubDateEnd)){
			polSubDateEnd=polSubDateEnd+" 23:59:59";
		}
		if(StrUtil.isNotEmpty(polBeginDateBegin)){
			polBeginDateBegin=polBeginDateBegin+" 00:00:00";
		}
		if(StrUtil.isNotEmpty(polBeginDateEnd)){
			polBeginDateEnd=polBeginDateEnd+" 23:59:59";
		}
		map.put("polSubDateBegin", polSubDateBegin);
		map.put("polSubDateEnd", polSubDateEnd);
		map.put("polBeginDateBegin", polBeginDateBegin);
		map.put("polBeginDateEnd", polBeginDateEnd);
		String channelCodeStr;
		if(StrUtil.isEmpty(policy.getPartnerNo())){
			channelCodeStr = "";
		}else{
			channelCodeStr=policy.getPartnerNo();
		}	
		map.put("channelCodeStr", channelCodeStr);
		if(StrUtil.isEmpty(userCode)){
			userCode = "";
		}
		map.put("userCode", userCode);
		map.put("planNo",StrUtil.isEmpty(policy.getProductCode())?"":policy.getProductCode());
		map.put("polno", policy.getPolno());
		map.put("stateId", policy.getStateId());
		page.setMap(map);
		return page;
	}
		
	//added by gzz@20151105 for shen zhen you hua begin 
	@RequestMapping(value = "/queryViewDetail", method = RequestMethod.POST)
	@ResponseBody public Page<Map<String, Object>> queryByTradNoticeId(String polNo,String tradProdType) throws Exception {
		Page<Map<String, Object>> page = new Page<Map<String,Object>>();
		if(StrUtil.isEmpty(polNo)){
			page.setResult("error");
			page.setMessage("请求参数错误，请稍后重试！");
			return page;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		// 逻辑处理思路：根据 产品类型进入相应的分支
		//1.根据保单号查询保单的相关信息
		//2.查询投被保人相关信息
		//3.查询受益人信息
		//4.查询险种信息
		GatewayPolicy policyInfo = lifePolicyListService.queryScanPolicyInfoByPolNo(polNo);//1.
		DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance();
        df.applyPattern("###,###,###,###,###,##0.00");
        if(null!=policyInfo && null!=policyInfo.getAmount()){
        	policyInfo.setAmountFormatStr(df.format(policyInfo.getAmount()));
        } 
        if(null!=policyInfo && null!=policyInfo.getPremium()){
        	policyInfo.setPremiumFormatStr(df.format(policyInfo.getPremium()));
        }
		//非即时起保保单保险止期应该是数据库所存日期的24:00:00
        if(null!=policyInfo && null!=policyInfo.getEndDateStr()){
        	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
    		String endDateStr = policyInfo.getEndDateStr();
    		policyInfo.setEndDateStr(sdf.format(sdf.parse(endDateStr)));
        }
		ScanCustomer tbrInfo=null;
		ScanCustomer bbrInfo=null;
		ScanCustomer syrInfo=null;
		//2.查询投被保人相关信息
		if(null!=policyInfo && StrUtil.isNotEmpty(policyInfo.getAppno())){
			tbrInfo  =  customerService.queryScanTBRInfoByAppNo(policyInfo.getAppno()); //2 tbr
		}
		if(null!=tbrInfo && StrUtil.isNotEmpty(tbrInfo.getRelWithInsured())){
			bbrInfo  =  customerService.queryScanBBRInfoByAppNo(policyInfo.getAppno()); //2 bbr
		}
		if(null != policyInfo && "01".equalsIgnoreCase(policyInfo.getAppoInt())){ //指定受益人时查询
			//3.查询受益人信息
			syrInfo = customerService.queryScanSYRInfoByAppNo(policyInfo.getAppno());//3 syr
		}
		List<NlifeCov> nLifeItemOrCovInfoLs = nlifeProdConfigService.queryItemsAndCovsInfoByPolicyId(policyInfo.getPolicyId());
		if( null!=nLifeItemOrCovInfoLs && nLifeItemOrCovInfoLs.size()>0){
			for (NlifeCov temFormat:nLifeItemOrCovInfoLs){
				if(null!=temFormat && null!= temFormat.getCovAmt()){
					temFormat.setCovAmtStr(df.format(temFormat.getCovAmt()));
				}
			}
		}
		map.put("policy_detail_Info", policyInfo);
		map.put("tbr_detail_Info", tbrInfo);
		map.put("bbr_detail_Info", bbrInfo);
		map.put("syr_detail_Info", syrInfo);
		map.put("nlife_xz_detail_Info", nLifeItemOrCovInfoLs);
		page.setObj(map);
		return page;
	}
	
	/**
     * 分页条件查询人险保单
     * @param session
     * @param pageIndex
     * @param policy
     * @param privilegeBranch
     * @param bbrName
     * @param bbrCertiCode
     * @param polSubDateBegin
     * @param polSubDateEnd
     * @param polBeginDateBegin
     * @param polBeginDateEnd
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryScanPolicyPageByCriteria")
    @ResponseBody
    public Page queryScanPolicyPageByCriteria(HttpSession session, Integer pageIndex,GatewayPolicy policy,String userCode,
                String polSubDateBegin,String polSubDateEnd,String polBeginDateBegin,String polBeginDateEnd) throws Exception {
        Page page = beforeQueryLifePolicyPageByCriteria(session, pageIndex, policy, userCode, polSubDateBegin, polSubDateEnd, polBeginDateBegin, polBeginDateEnd);
        return lifePolicyListService.queryScanPolicyPageByCriteria(page);
    }
    
    /**
	 * 查询方案列表
	 * @param size
	 * @param current
	 * @param tradProdCode
	 * @throws Exception 
	 */
	@RequestMapping(value = "/queryPlanList")
	public @ResponseBody Page<Map<String,Object>> queryPlanList(Integer size,Integer current,String planCode,String planName,HttpSession session,String partnerNo) throws Exception{
		Page<Map<String,Object>> page=new Page<Map<String,Object>>();
		page.setCurrent(current);
		page.setSize(size);
		GatewayUser user=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("planCode", StrUtil.isEmpty(planCode)?null:planCode);
		map.put("planName", StrUtil.isEmpty(planName)?null:planName);
		map.put("partnerNo", StrUtil.isEmpty(partnerNo)?null:partnerNo);
		page.setMap(map);
		return ruleConfigerService.queryPlanPageByCriteria(page, user);
	}
    
    /**
     * 查询总量
     * @param session
     * @param pageIndex
     * @param policy
     * @param privilegeBranch
     * @param bbrCertiCode
     * @param polSubDateBegin
     * @param polSubDateEnd
     * @param polBeginDateBegin
     * @param polBeginDateEnd
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryScanPolicyAll")
    @ResponseBody
    public Map<String, String> queryLifePolicyAll(HttpSession session,String userCode,
            GatewayPolicy policy,String polSubDateBegin,String polSubDateEnd,String polBeginDateBegin,String polBeginDateEnd) throws Exception {

        Page page = beforeQueryLifePolicyPageByCriteria(session, -1, policy,userCode, polSubDateBegin, polSubDateEnd, polBeginDateBegin, polBeginDateEnd);
        Map<String,String> map = (Map<String, String>) page.getMap();
        
        return lifePolicyListService.queryLifePolicyAll(map);
    }
    
    
    /**
     * 下载人险保单信息
     * @param session
     * @param policy
     * @param privilegeBranch
     * @param bbrName
     * @param bbrCertiCode
     * @param polSubDateBegin
     * @param polSubDateEnd
     * @param polBeginDateBegin
     * @param polBeginDateEnd
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/downloadLifePolicyFileByCriteria")
    public void downloadLifePolicyFileByCriteria(HttpSession session,HttpServletResponse response,String userCode,
            GatewayPolicy policy,String polSubDateBegin,String polSubDateEnd,String polBeginDateBegin,String polBeginDateEnd) throws Exception {
        
        Page page = beforeQueryLifePolicyPageByCriteria(session, -1,policy,userCode, polSubDateBegin, polSubDateEnd, polBeginDateBegin, polBeginDateEnd);
        
        Map<String,Object> map = (Map<String, Object>) page.getMap();
        List<Map<String, Object>> lifePolicyList = lifePolicyListService.queryScanPolicyListByCriteria(map);
        lifePolicyListService.downloadLifePolicyFile(lifePolicyList, response);
    }
    
    
    @RequestMapping(value = "/reSendEmail", method = RequestMethod.POST)
	@ResponseBody
	public Result reSendEmail(String polNo,String email) throws Exception {
		logger.info("邮件重发： polNo: "+polNo+" 邮箱地址："+email);
		if(StrUtil.isEmpty(polNo)){
			return Result.fail("参数有误");
		}
		if(StrUtil.isEmpty(email)){
			return Result.fail("邮箱不能为空");
		}
		return lifePolicyListService.addEmailReSend(polNo, email);
	}
	
	@RequestMapping(value = "/reSendSms", method = RequestMethod.POST)
	@ResponseBody
	public Result reSendSms(String polNo,String phoneNo) throws Exception {
		logger.info("短信重发： polNo: "+polNo+" 邮箱地址："+phoneNo);
		if(StrUtil.isEmpty(polNo)){
			return Result.fail("参数有误");
		}
		if(StrUtil.isEmpty(phoneNo)){
			return Result.fail("手机号不能为空");
		}
		return lifePolicyListService.addSMSReSend(polNo, phoneNo);
	}
}
